package com.lifuixng.picturebackend.manage;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.lifuixng.picturebackend.config.CosClientConfig;
import com.lifuixng.picturebackend.exception.BusinessException;
import com.lifuixng.picturebackend.exception.ErrorCode;
import com.lifuixng.picturebackend.exception.ThrowUtils;
import com.lifuixng.picturebackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author Mr.LiFuXing
 * @Date 2024/12/18 19:35
 * @Title FileManage
 * @Package com.lifuixng.picturebackend.manage
 */
@Slf4j
@Component
@Deprecated
public class FileManage {


    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;


    /**
     * 上传图片（返回解析图片的信息对象）
     *
     * @param multipartFile       上传的文件
     * @param uploadPicturePrefix 上传路径前缀 /test
     * @return R
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPicturePrefix) {
        // 图片校验
        verifyPicture(multipartFile);
        // 2. 以防图片名称重复覆盖图片，自己生成一个唯一的图片名
        // day+uuid+.jpg
        String uuid = RandomUtil.randomString(8);
        String originalFilename = multipartFile.getOriginalFilename();
        // 生成图片的全名称 2024-12-18-12345678.jpg
        String uploadFilename = String.format("%s-%s.%s",
                DateUtil.formatDate(new Date()),
                uuid,
                FileUtil.getSuffix(originalFilename));

        // 上传的位置（路径） 前缀＋图名全名 /test/2024-12-18-12345678.jpg
        String uploadPath = String.format("/%s/%s", uploadPicturePrefix, uploadFilename);
        // 3. 图片上传
        File file = null;
        try {
            file = File.createTempFile(uploadPath, null);
            multipartFile.transferTo(file);
            // 图片上传返回图片对象
            PutObjectResult objectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取到图片信息对象 （数据万象处理）
            ImageInfo imageInfo = objectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            // 计算宽高比
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            // 封装UploadPictureResult对象(图片的详细信息)
            return UploadPictureResult.builder()
                    .picFormat(imageInfo.getFormat())
                    .picName(FileUtil.mainName(originalFilename))
                    .picWidth(picWidth)
                    .picHeight(picHeight)
                    .picScale(picScale)
                    .picSize(FileUtil.size(file))
                    // https://li-yoy-picture-1333315463.cos.ap-beijing.myqcloud.com/图片路径
                    .url(cosClientConfig.getHost() + "/" + uploadPath)
                    .build();
        } catch (Exception e) {
            log.error("图片上传到COS失败！", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片上传失败");
        } finally {

            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    log.error("文件销毁失败{}", file.getAbsoluteFile());
                }
            }
        }
    }

    /**
     * 图片校验
     *
     * @param multipartFile
     */
    public void verifyPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 1. 校验图片 大小 图片类型
        long filesize = multipartFile.getSize();
        // 1M
        final long ONE_M = 1024 * 1024L;
        ThrowUtils.throwIf(filesize > ONE_M * 2, ErrorCode.OPERATION_ERROR, "上传图片大小不能超过2M");
        // 获取文件的后缀名 jpg png
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> ALLOW_SUFFIX = Arrays.asList("jpg", "png", "webp", "jpeg");
        ThrowUtils.throwIf(!ALLOW_SUFFIX.contains(fileSuffix), ErrorCode.SYSTEM_ERROR, "文件类型错误");
    }


    /**
     * 通过URL上传图片（返回解析图片的信息对象）
     *
     * @param fileUrl             上传的文件
     * @param uploadPicturePrefix 上传路径前缀 /test
     * @return R
     */
    public UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPicturePrefix) {
        // 图片校验
        validPicture(fileUrl);
        // 2. 以防图片名称重复覆盖图片，自己生成一个唯一的图片名 day+uuid+.jpg
        String uuid = RandomUtil.randomString(8);
        // String originalFilename = fileUrl.getOriginalFilename();
        String originalFilename = FileUtil.mainName(fileUrl);
        // 生成图片的全名称 2024-12-18-12345678.jpg
        String uploadFilename = String.format("%s-%s.%s",
                DateUtil.formatDate(new Date()),
                uuid,
                FileUtil.getSuffix(originalFilename));

        // 上传的位置（路径） 前缀＋图名全名 /test/2024-12-18-12345678.jpg
        String uploadPath = String.format("/%s/%s", uploadPicturePrefix, uploadFilename);
        // 3. 图片上传
        File file = null;
        try {
            file = File.createTempFile(uploadPath, null);
            // fileUrl.transferTo(file);
            HttpUtil.downloadFile(fileUrl, file);
            // 图片上传返回图片对象
            PutObjectResult objectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取到图片信息对象 （数据万象处理）
            ImageInfo imageInfo = objectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            // 计算宽高比
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            // 封装UploadPictureResult对象(图片的详细信息)
            return UploadPictureResult.builder()
                    .picFormat(imageInfo.getFormat())
                    .picName(FileUtil.mainName(originalFilename))
                    .picWidth(picWidth)
                    .picHeight(picHeight)
                    .picScale(picScale)
                    .picSize(FileUtil.size(file))
                    // https://li-yoy-picture-1333315463.cos.ap-beijing.myqcloud.com/图片路径
                    .url(cosClientConfig.getHost() + "/" + uploadPath)
                    .build();
        } catch (Exception e) {
            log.error("图片上传到COS失败！", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片上传失败");
        } finally {

            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    log.error("文件销毁失败{}", file.getAbsoluteFile());
                }
            }
        }
    }


    /**
     * 校验URL
     *
     * @param fileUrl
     */
    private void validPicture(String fileUrl) {
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");

        try {
            // 1. 验证 URL 格式
            new URL(fileUrl); // 验证是否是合法的 URL
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }

        // 2. 校验 URL 协议
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")),
                ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");

        // 3. 发送 HEAD 请求以验证文件是否存在
        HttpResponse response = null;
        try {
            response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            // 未正常返回，无需执行其他判断
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 4. 校验文件类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
            // 5. 校验文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long TWO_MB = 2 * 1024 * 1024L; // 限制文件大小为 2MB
                    ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }


}
